package com.jrx.anytxn.transaction.job.paph.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.service.impl.interestFileServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class TraAcctDetailListener implements JobExecutionListener {
    @Autowired
    private PaphFileConfig paphFileConfig;
    @Autowired
    private IOrganizationTableService organizationTableService;

    private static final Logger logger = LoggerFactory.getLogger(interestFileServiceImpl.class);


    @Override
    public void beforeJob(JobExecution jobExecution) {
        this.checkFile(Constant.PRODECUT_TYPE_XF);
        this.checkFile(Constant.PRODECUT_TYPE_JY);
    }

    private void checkFile(String productType) {
        String planFilePath = paphFileConfig.getTraAcctDetailFilePath();
        String fileType = paphFileConfig.getFileType();

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        String toDay = DateUtils.format(org.getNextProcessingDate(), "yyyyMMdd");
        String planFileName = Constant.LS_BANK + productType + "_" + toDay + "_" + TransBizConstant.TRA_ACCT_DETAIL + "_" + fileType + ".txt";

        String filePath = planFilePath + org.getTenantId() + File.separator + toDay + File.separator + productType + File.separator;

        Path planFile = Paths.get(filePath + planFileName);
        Path pFile = Paths.get(filePath);

        if (!Files.exists(planFile)) {
            //判断文件夹是否存在
            if (!Files.isDirectory(pFile)) {
                //创建文件夹
                try {
                    Files.createDirectories(pFile);
                } catch (IOException e) {
                    logger.error("创建目录失败", e);
                    throw new RuntimeException(e);
                }
            }
        } else {
            try {
                Files.delete(planFile);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        //创建文件
        try {
            Files.createFile(planFile);
        } catch (IOException e) {
            logger.error("创建文件失败", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {

    }
}
